//
//  JCVideoPlayer.m
//  JCVideoPlayer
//
//  Created by Guo.JC on 2017/5/15.
//  Copyright © 2017年 Guo.JC. All rights reserved.
//

#import "JCVideoPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "HighlightPropertyView.h"
#import "TrackVideo.h"

@interface JCVideoPlayer ()
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (weak, nonatomic) IBOutlet UIButton *preBtn;
@property (weak, nonatomic) IBOutlet UIView *progressBoard;
@property (weak, nonatomic) IBOutlet UIView *progressView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bufferProgress;
@property (weak, nonatomic) IBOutlet UIView *bufferView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *slideWidth;
@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (strong, nonatomic) AVPlayerItem *playerItem;
@property (assign, nonatomic) CMTime totalTime;
@property (strong, nonatomic) NSTimer *updateTimer;
@property (weak, nonatomic) IBOutlet UIView *playerView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loading;
@property (assign, nonatomic) BOOL isFinishCurrent;
@property (weak, nonatomic) IBOutlet UIView *topBar;
@property (weak, nonatomic) IBOutlet UIView *bottomBar;
@property (strong, nonatomic) NSTimer *hidenToolBarTimer;
@property (weak, nonatomic) IBOutlet UIView *leftAnimated;
@property (strong, nonatomic) HighlightPropertyView *leftAnimatedView;
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftAnimatedViewWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftAnimatedViewHeight;
@property (assign, nonatomic) CGFloat height;

/** 当前播放的视频 */
@property (nonatomic, strong) TrackVideo *currentVideo;

@end

#define kStatus @"status"

@implementation JCVideoPlayer

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initPlayer];
    [self configureArcViews];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    CGFloat height = MAX(kYFScreenHeight, kYFScreenWidth);
    _height = (height == 568)?180:(height == 667) ?213:230;
    _leftAnimatedViewHeight.constant = _height;
}

- (void)configureArcViews {
    if (!self.leftAnimatedView) {
        self.leftAnimatedView = [[HighlightPropertyView alloc] initWithFrame:self.leftAnimated.bounds];
        [self.leftAnimated addSubview: self.leftAnimatedView];
    }
    CGFloat _videoAspect = 720.0/1280.0;
    _leftAnimated.frame = CGRectMake(0, kYFScreenHeight / 2 - (kYFScreenWidth * _videoAspect) / 2, 70, kYFScreenWidth * _videoAspect);
}

- (void)initPlayer{
    
    _progressView.layer.cornerRadius = _progressBoard.layer.cornerRadius = _bufferView.layer.cornerRadius = 3;
    _progressView.layer.masksToBounds = _progressBoard.layer.masksToBounds = _bufferView.layer.masksToBounds = YES;
    [_loading stopAnimating];
    _isFinishCurrent = NO;
    if (_index == 0) {
        _preBtn.enabled = NO;
    }
    if (_index == _videoFiles.count - 1) {
        _nextBtn.enabled = NO;
    }
    // setAVPlayer
    _player = [[AVPlayer alloc] init];
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    _playerLayer.frame = _playerView.bounds;
    [_playerView.layer addSublayer:_playerLayer];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setPlayerUrl];
}

// 设置播放URL
- (void)setPlayerUrl {
    if (self.videoFiles.count > self.index){
        self.currentVideo = self.videoFiles[self.index];
        NSURL *videoUrl = [NSURL fileURLWithPath:self.currentVideo.documentPath];
        [self updatePlayerWithURL:videoUrl];
    }
}

- (void)updatePlayerWithURL:(NSURL *)url {
    _playBtn.selected = YES;
    [_loading startAnimating];
    _slideWidth.constant = 0;
    if (_updateTimer) {
        [_updateTimer invalidate];
        _updateTimer = nil;
    }
    if (_playerItem) {
        [_playerItem removeObserver:self forKeyPath:kStatus];
    }
    _playerItem = [AVPlayerItem playerItemWithURL:url]; // create item
    [_player  replaceCurrentItemWithPlayerItem:_playerItem];
    [self addObserverAndNotification];
    
}

- (void)addObserverAndNotification{
    [_playerItem addObserver:self
                  forKeyPath:kStatus
                     options:(NSKeyValueObservingOptionNew)
                     context:nil];
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playbackFinished:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:self.player.currentItem];
}

-(void)playbackFinished:(NSNotification *)notification{
    NSLog(@"视频播放完成.");
    _playBtn.selected = NO;
    _isFinishCurrent = YES;
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    AVPlayerItem *item = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:kStatus]) {
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue]; // 获取更改后的状态
        if (status == AVPlayerStatusReadyToPlay) {
            _totalTime = item.duration; // 获取视频长度
            // 设置视频时间
//            [self setMaxDuration:CMTimeGetSeconds(duration)];
            // 播放
            [_player play];
            if (_updateTimer == nil) {
                _updateTimer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(updateData) userInfo:nil repeats:YES];
            }
            [_loading stopAnimating];
            _playBtn.selected = YES;
        } else if (status == AVPlayerStatusFailed) {
            YFLog(@"播放失败");
            [_loading stopAnimating];
        } else {
            YFLog(@"未知错误");
            [_loading stopAnimating];
        }
        
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDurationRanges]; // 缓冲时间
        CGFloat totalDuration = CMTimeGetSeconds(_playerItem.duration); // 总时间
        [self setProgress:timeInterval / totalDuration animated:YES]; // 更新缓冲条
    }
}
- (void)updateData{
    [self setProgress:(CMTimeGetSeconds(_playerItem.currentTime) / CMTimeGetSeconds(_playerItem.duration)) animated:YES];
    // 更新左侧数据
    NSTimeInterval currentTime = CMTimeGetSeconds(_playerItem.currentTime);
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"swingSecond = %d",
                         (int)currentTime];
    RLMResults *videoTrackItems = [self.currentVideo.videoTrackItems objectsWithPredicate:pred];
    if ([videoTrackItems count] > 0) {
        VideoTrackItem *trackItem = [videoTrackItems lastObject];
        [self updateLeftAirView:trackItem];
    }
    //                    NSLog(@"搜索到的挥拍:%@", videoTrackItems);
}

- (void)updateLeftAirView:(VideoTrackItem *)item {
    [_leftAnimatedView animateToValues:@[@(item.speed),@(item.strength),@(item.swingTime)]];
}
// 已缓冲进度
- (NSTimeInterval)availableDurationRanges {
    NSArray *loadedTimeRanges = [_playerItem loadedTimeRanges]; // 获取item的缓冲数组
    // discussion Returns an NSArray of NSValues containing CMTimeRanges
    
    // CMTimeRange 结构体 start duration 表示起始位置 和 持续时间
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue]; // 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds; // 计算总缓冲时间 = start + duration
    return result;
}

- (void)setProgress:(CGFloat)progress animated:(BOOL)animated {
    
    if (animated) {
        [UIView animateWithDuration:10 animations:^{
            _slideWidth.constant = progress * _progressBoard.bounds.size.width;
        }];
    }
    else{
        _slideWidth.constant = progress * _progressBoard.bounds.size.width;
    }
}

#pragma mark - Action
- (IBAction)playAction:(UIButton *)sender {
    if (sender.selected == NO) {
        if (_isFinishCurrent == YES) {
            [self setPlayerUrl];
            _isFinishCurrent = NO;
        }else{
           [_player play];
        }
    }
    else{
        [_player pause];
    }
    sender.selected = !sender.selected;
}

- (IBAction)preAction:(UIButton *)sender {

    if (_index == 0) {
//        [self alertMessage:@"已经是第一个视频了"];
        return;
    }
    _index--;
     [self setPlayerUrl];
    _nextBtn.enabled = YES;
    if (_index == 0) {
        _preBtn.enabled = NO;
    }
}

- (IBAction)nextAction:(UIButton *)sender {
    if (_index == _videoFiles.count - 1) {
//        [self alertMessage:@"已经是最后一个视频了"];
        return;
    }
    _index++;
     [self setPlayerUrl];
    _preBtn.enabled = YES;
    if (_index == _videoFiles.count - 1) {
        _nextBtn.enabled = NO;
    }
}

- (IBAction)closeAction:(UIButton *)sender {
    
    if (_updateTimer) {
        [_updateTimer invalidate];
        _updateTimer = nil;
    }
    [_player replaceCurrentItemWithPlayerItem:nil];
    [_playerItem removeObserver:self forKeyPath:kStatus];
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];
    [self dismissViewControllerAnimated:YES completion:nil];
    self.player = nil;
    [self.playerLayer removeFromSuperlayer];
    self.playerLayer = nil;
}

- (IBAction)changeScreenDir:(UIButton *)sender {
    
    if (sender.selected) {
        [self orientationChange:NO];
    }
    else{
         [self orientationChange:YES];
    }
    [UIView animateWithDuration:.5 animations:^{
        _playerLayer.frame = _playerView.bounds;
    }];
    sender.selected = !sender.selected;
}

#pragma mark - 屏幕旋转
- (void)orientationChange:(BOOL)landscapeRight
{
    CGFloat _videoAspect = 720.0/1280.0;
    if (landscapeRight) {
        _leftAnimatedViewHeight.constant = kYFScreenWidth;
        [UIView animateWithDuration:0.2f animations:^{
            [self.leftAnimated setNeedsLayout];
            self.view.transform = CGAffineTransformMakeRotation(M_PI_2);
            CGRect bouns = CGRectMake(0, 0, kYFScreenHeight, kYFScreenWidth);
            self.view.bounds = bouns;
            self.playerView.frame = bouns;
            self.playerLayer.frame = self.playerView.bounds;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:.2 animations:^{
                [self.leftAnimatedView configFrame:self.leftAnimated.bounds];
            }];
        }];
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:YES];
        [self.view bringSubviewToFront:_topBar];
        
    } else {
        _leftAnimatedViewHeight.constant = _height;
        [UIView animateWithDuration:0.2f animations:^{
            [self.leftAnimated setNeedsLayout];
            self.view.transform = CGAffineTransformMakeRotation(0);
            CGRect bouns = CGRectMake(0, 0, kYFScreenWidth, kYFScreenHeight);
            self.view.bounds = bouns;
            self.playerView.frame = bouns;
            self.playerLayer.frame = self.playerView.bounds;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:.2 animations:^{
                [self.leftAnimatedView configFrame:self.leftAnimated.bounds];
            }];
        }];
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES];
    }
}

#pragma mark- sizeClass 横竖屏约束
// sizeClass 横竖屏切换时，执行
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    // 横竖屏切换时重新添加约束
    CGRect bounds = [UIScreen mainScreen].bounds;
    _playerView.frame = bounds;
    _playerLayer.frame = bounds;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    //viewController初始显示的方向
    return UIInterfaceOrientationPortrait;
}

//工具栏隐藏或者出现
- (IBAction)switchToolBar:(UITapGestureRecognizer *)sender {
    
    if (_topBar.alpha == 0) {
        [self hidenToolBar:NO];
    }else{
        [self hidenToolBar:YES];
    }
}

- (void)hidenToolBar:(BOOL)hiden{
    [UIView animateWithDuration:.3 animations:^{
        _topBar.alpha = !hiden;
        _bottomBar.alpha = !hiden;
    }];
}

- (void)dealloc{
    YFLog(@"释放播放器");
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
